package com.hrbxlh.action;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.hrbxlh.actionImpl.*;
import com.hrbxlh.util.ConfigFileUtil;
import com.hrbxlh.util.FileUpload;
import com.hrbxlh.util.PubMethods;
import com.hrbxlh.util.SessionValues;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
* -------------------------------------------------------
* Copyright (c) 2017, 鑫联华信息科技股份有限公司
* All rights reserved.
* FileName：ClassAction.java
* Description：班级action类
* History：
* Date           Author               Desc
* 2017.3.29		  sy                   建立
* 2017.6.8		xzx					进行2.0的添加班级、修改班级、班级详情修改
* -------------------------------------------------------
*/
@Controller
public class ClassAction {
	
	@Autowired
	@Qualifier("classActionImpl")
	private ClassActionImpl classActionImpl;
	
	@Autowired
	@Qualifier("memberActionImpl")
	private MemberActionImpl memberActionImpl;
	
	@Autowired
	@Qualifier("relStuClassActionImpl")
	private RelStuClassActionImpl relStuClassActionImpl;
	
	@Autowired
	@Qualifier("courseActionImpl")
	private CourseActionImpl courseActionImpl;


	@Autowired
	@Qualifier("relationActionImpl")
	private RelationActionImpl relationActionImpl;
	
	//日志信息
	Logger logger = Logger.getLogger(ClassAction.class.getName());
	
	/**
	 * @param request
	 * @param response
	 * @return  跳转到添加班级页面
	 * @throws IOException
	 */
	@RequestMapping(value = "/skipAddClass", method = RequestMethod.GET)
	public ModelAndView skipAddClass(String jsonStr,HttpServletRequest request, HttpServletResponse response) throws IOException {		
		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放返回值
		Map<String, Object> returnMap = new HashMap<String, Object>();
		//返回字符串
		String reJsonStr = "";
		//存放页面
		String pageName = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		try {
			//添加页面名称
			pageName = "pc/addClass";
		} catch (Exception e) {
			resultMap.put("errMsg", "跳转页面失败");
			e.printStackTrace();
			logger.error("跳转添加班级页面出现异常", e);
			pageName = "public/pageerror";
		} finally {
			reJsonStr = mapper.writeValueAsString(resultMap);
			returnMap.put("result", reJsonStr);
			logger.info("返回的  :" + reJsonStr);
		}
		return new ModelAndView(pageName, returnMap);
	}

	/**
	 * @description 查询某个课类型为教师排课的上课老师
	 * @param request
	 * @param response
	 * @return  课程主键id 
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getTeacherByCourse", method = RequestMethod.POST)
	public void  getTeacherByCourse (HttpServletResponse response, String jsonStr)  {
		
		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		try { 
			//获取参数值  课程id
			Map<String,Object> paramMap = mapper.readValue(jsonStr, resultMap.getClass());
			//通过课程id查询类型为教师排课的教师信息
			Map<String,Object> teacherDetail = classActionImpl.getTeacherByCourseIdAndMark(paramMap);
			resultMap.put("teacherDetail", teacherDetail);
			logger.info("查询某个课程的上课老师,参数为："+jsonStr);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("查询某个课程的上课老师出现异常getTeacherByCourse", e);
		} finally {
			try {
				courseActionImpl.responseStream(response, mapper.writeValueAsString(resultMap));
			} catch (JsonProcessingException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**xzx
	 * @param response
	 * @return  添加班级。 班级详细信息，和（教师id、课程id的列表）
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/addClass", method = RequestMethod.POST)
	public void addClass(String jsonStr, HttpServletResponse response) {
		
		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//成功失败标识
		String resultMark = "fail";
		try {
			//获取参数值
			Map<String,Object> paramMap = mapper.readValue(jsonStr, resultMap.getClass());
			if (courseActionImpl.paramCheck(paramMap.get("className"), response, resultMap, mapper)) return;
			//添加班级
			Map<String, Object> resultFlag = classActionImpl.addClass(paramMap);
			resultMark = ((Boolean)resultFlag.get("result")) ? "success" : "fail";
			resultMap.put("result", resultMark);
			if(resultMark.equals("fail")){
				resultMap.put("failMsg", resultFlag.get("failMsg"));
			}
			logger.info("添加班级,参数为："+jsonStr);
			courseActionImpl.responseStream(response, mapper.writeValueAsString(resultMap));
		} catch (Exception e) {
			resultMap.put("result", "fail");
			e.printStackTrace();
			logger.error("添加班级出现异常addClass", e);
			try {
				courseActionImpl.responseStream(response, mapper.writeValueAsString(resultMap));
			} catch (JsonProcessingException e1) {
				e1.printStackTrace();
			}
		}
	}
	
	/**
	 * @param request
	 * @param response
	 * @return  修改班级弹出框获取数据。  classId
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/skipSaveClass", method = RequestMethod.POST)
	public void skipSaveClass(String jsonStr, HttpServletRequest request, HttpServletResponse response)  {
		
		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		try {
			//获取页面参数值
			Map<String,Object> preParamMap = mapper.readValue(jsonStr, resultMap.getClass());
			//班级信息
			Map<String, Object> classMap = classActionImpl.getClass(preParamMap);
			//返回值 班级信息
			resultMap.put("classList", classMap.get("resultList")); 
			//专业信息
			resultMap.put("proList", classMap.get("proList")); 
			//返回关联信息，下面带加号的 ,参数是班级id
			List<Map<String, Object>> relationList = classActionImpl.getClassRelation(preParamMap);
			resultMap.put("relationList", relationList);
			logger.info("跳转修改班级页面,参数为："+jsonStr);
		} catch (Exception e) {
			resultMap.put("errMsg", "跳转页面失败");
			e.printStackTrace();
			logger.error("跳转修改班级页面出现异常skipSaveClass", e);
		} finally {
			try {
				courseActionImpl.responseStream(response, mapper.writeValueAsString(resultMap));
			} catch (JsonProcessingException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * @param request
	 * @param response  
	 * @return  修改班级.
	 * 1班级基本信息   classId  className professionId 
	 * 2原来有的关联删除的  delList   需要：classId stuorteaId courseId
	 * 3 新加的关联  addList 需要：courseId stuorteaId
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/saveClass", method = RequestMethod.POST)
	public void saveClass(String jsonStr , HttpServletResponse response) {

		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//成功失败标识
		String resultMark = "fail";
		try {
			//获取参数值
			Map<String,Object> paramMap = mapper.readValue(jsonStr, resultMap.getClass());
			if (courseActionImpl.paramCheck(paramMap.get("className"), response, resultMap, mapper)) return;
			//修改班级
			Map<String,Object> returnMap = classActionImpl.saveClass(paramMap);
			boolean flag = (Boolean)returnMap.get("result");
			resultMark = (flag == true) ? "success" : "fail";
			resultMap.put("result", resultMark);
			resultMap.put("failMsg", returnMap.get("failMsg"));
			logger.info("修改班级,参数为："+jsonStr);
			courseActionImpl.responseStream(response, mapper.writeValueAsString(resultMap));
		} catch (Exception e) {
			resultMap.put("result", "fail");
			e.printStackTrace();
			logger.error("修改班级出现异常saveClass", e);
			try {
				courseActionImpl.responseStream(response, mapper.writeValueAsString(resultMap));
			} catch (JsonProcessingException e1) {
				e1.printStackTrace();
			}
		}
	}
	
	/**
	 * @param request
	 * @param response
	 * @return  删除班级,传回班级id集合。List<String>形式   jsonStr = ["1","2","3"...]
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/delClass", method = RequestMethod.POST)
	public void delClass(String jsonStr, HttpServletRequest request, HttpServletResponse response) throws IOException {

		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//返回字符串
		String reJsonStr = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		String errorMsg = "";
		//成功失败标识
		String resultMark = "fail";
		Map<String,Object> paramMap = new HashMap<String,Object>();
		try{
			//获取参数值
			paramMap = mapper.readValue(jsonStr, paramMap.getClass());
			List<String> paramList = (List<String>) paramMap.get("list");
			int marks = Integer.valueOf(String.valueOf(paramMap.get("marks")));
			//通过classId查询班级状态，正在考试中的班级不可以删除
			Map<String,Object> classMap = classActionImpl.getClassStateList(paramList);
			if(String.valueOf(classMap.get("result")).equals("fail")){
				errorMsg = String.valueOf(classMap.get("msg"));
				resultMark = "fail";
			}else{
				//xzx获取要删除的班级的关联
				List<Map<String,Object>> relaList = relationActionImpl.getDelRelation(paramList);
				//删除班级
				boolean flag = classActionImpl.delClass(paramList,marks);
				if(flag){
					//xzx修改教师与课程的关联信息
					flag = relationActionImpl.saveTeaReCourseMark(paramList, relaList);
				}
				resultMark = (flag == true) ? "success" : "fail";

				if(resultMark.equals("fail")){
					errorMsg = "删除班级失败";
				}
			}
			resultMap.put("result", resultMark);
			resultMap.put("errorMsg",errorMsg);
			logger.info("删除班级的参数为："+jsonStr);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("删除班级出现异常", e);
		} finally {
			reJsonStr = mapper.writeValueAsString(resultMap);
			logger.info("删除班级给前台返回的结果："+reJsonStr);
			response.setContentType("text/html;charset=UTF-8");
			PrintWriter write = response.getWriter();
			write.println(reJsonStr);
			write.flush();
		}
	}

	/**
	 * @param pageNow,pageSize(一般是10)，页数从1开始，第一页pageNow传1
	 * @return  班级列表页面，传回全部班级信息。进页面，翻页，条件查询都是这个。
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getClassList", method = RequestMethod.POST)
	public void getClassList(String jsonStr, HttpServletRequest request, HttpServletResponse response) throws IOException {

		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放返回值
		Map<String, Object> returnMap = new HashMap<String, Object>();
		//返回字符串
		String reJsonStr = "";
		//存放页面
		String pageName = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();

		try {

			//获取页面参数值
			Map<String, Object> preParamMap = mapper.readValue(jsonStr, returnMap.getClass());
			//搜索框对象
			Map<String, Object> SearObjectMap = new HashMap<String,Object>();
			if(preParamMap.get("departmentName")!=null){
				SearObjectMap.put("departmentName", preParamMap.get("departmentName"));
				SearObjectMap.put("departmentId", preParamMap.get("departmentId"));
			}
			//获取人员列表信息
			Map<String, Object> resultAllMap = classActionImpl.getClassList(preParamMap);

			//返回值
			resultMap.put("classList", resultAllMap.get("classList"));
			resultMap.put("selectclaList", resultAllMap.get("selectclaList"));
			resultMap.put("departMentList", resultAllMap.get("departMentList"));
			resultMap.put("SearObjectMap", SearObjectMap);
			resultMap.put("totalPage", resultAllMap.get("totalPage"));
			resultMap.put("pageNow", resultAllMap.get("pageNow"));
			resultMap.put("pageSize", preParamMap.get("pageSize"));
			//查询全部课程
			preParamMap.put("releaseMark",1);
			List<Map<String, Object>> courseList = courseActionImpl.getAllCourse(preParamMap);
			resultMap.put("courseList", courseList);
			//查询全部老师
			List<Map<String, Object>> teacherList = memberActionImpl.getTeachers();
			resultMap.put("teacherList", teacherList);
			resultMap.put("result", "success");
			resultMap.put("failMsg", "");
			logger.info("跳转班级列表页面的参数为"+jsonStr);
		} catch (Exception e) {
			resultMap.put("result", "fail");
			resultMap.put("failMsg", "跳转页面失败");
			e.printStackTrace();
			logger.error("跳转班级列表页面出现异常", e);

		} finally {
			logger.info("跳转班级列表页面返回的结果为"+resultMap);
			PubMethods.postMed(response,mapper,resultMap);
		}


	}
	
	/**
	 * 导入学生
	 * @param file
	 * @param response
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/imStuExcelByClass", method=RequestMethod.POST)
	public void imStuExcelByClass(@RequestParam("file") CommonsMultipartFile file,int classId,String type, HttpServletResponse response, HttpServletRequest request) throws Exception {
		 String fileName =  file.getOriginalFilename();
		 String view ="";
		 String reJsonStr = "";
		 ObjectMapper mapper = new ObjectMapper();
		 Map<String,Object> map = new HashMap<String,Object>();
		 //获取当前登陆人选择的角色
		Map<String, Object> sessionMap = new SessionValues().getSessionValues(new String[] {"roleId"}, request, "userMsg");
		int  selecetRoleId = Integer.parseInt(String.valueOf(sessionMap.get("roleId")));

	
		Map<String,Object> resultMap = new HashMap<String ,Object>();
		 try{
			 //获取文件后缀
			 String allFileName=file.getName();
			 String prefix=fileName.substring(fileName.lastIndexOf(".")+1);
			 if(!prefix.equals("xls")){
				 resultMap.put("msg","fail");
				 resultMap.put("errMsg","请将文件改为excel2003版");
				 return;
			 }
			  String path = request.getSession().getServletContext().getRealPath("/upload/" + fileName);// 存放位置
			  File destFile = new File(path);
			  logger.info(destFile);
			  String file1 = String.valueOf(destFile);
			  FileUtils.copyInputStreamToFile(file.getInputStream(), destFile);// 复制临时文件到指定目录下
			 resultMap = classActionImpl.imStuExcelByClass(file1,classId,type);
			 if((String.valueOf(resultMap.get("errMsg")).equals("null")||resultMap.get("errMsg")==null||String.valueOf(resultMap.get("errMsg")).equals(""))&&
					 String.valueOf(resultMap.get("result")).equals("fail")){
				 resultMap.put("errMsg","导入模板异常，请重新上传");
			 }
			 //将临时存到文件删除
			 PubMethods.delTempFile(fileName);
			 logger.info("导入学生或教师的班级id"+classId+"导入类型为"+type);
			  
		 }catch(Exception e){
			e.printStackTrace();
			map.put("errMsg", "导入失败");
			e.printStackTrace();
			logger.error("导入学生或教师出现异常", e);
			
		 }finally{
			 logger.info("导入学生或教师返回的结果为"+resultMap);
			PubMethods.postMed(response,mapper,resultMap);
		 }
	}
	

	/**
	 * @param 班号
	 * @return  班级详情。
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getDetailClass", method = RequestMethod.POST)
	public void getDetailClass(String jsonStr, HttpServletRequest request, HttpServletResponse response) throws IOException {

		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放返回值
		Map<String, Object> returnMap = new HashMap<String, Object>();
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
	
		try {
			/*模拟参数开始*/
			/*Map<String, Object> mapUse = new HashMap<String, Object>();
			mapUse.put("classId", 3);
			mapUse.put("pageNow", 1);
			mapUse.put("pageSize", 10);
			jsonStr = mapper.writeValueAsString(mapUse);*/
			/*模拟参数结束*/

			//获取页面参数值
			Map<String, Object> preParamMap = mapper.readValue(jsonStr, returnMap.getClass());
			//搜索框对象
			Map<String, Object> SearObjectMap = new HashMap<String,Object>();
			if(preParamMap.get("userName")!=null){
				SearObjectMap.put("userName", preParamMap.get("userName"));
			}
			//获取班级下的人员列表信息
			Map<String, Object> returnAllMap = memberActionImpl.getMemberList(preParamMap,request);
			//获取该班级对应的课程以及任课教师信息
			List<Map<String, Object>> courseList = classActionImpl.getCourseByClassId(preParamMap);
			resultMap.put("courseList", courseList);
			//查询当前人的消息
		/*	List<Map<String, Object>> noticeList = courseActionImpl.getMyNotice(request);
			//获取班级名
			resultMap.put("className", classActionImpl.getClassMsgById(preParamMap).get("className":));
			resultMap.put("noticeList", noticeList);*/
			//返回值
			resultMap.put("SearObjectMap", returnAllMap.get("SearObjectMap"));
			resultMap.put("memberList", returnAllMap.get("memberList"));
			resultMap.put("totalPage", returnAllMap.get("totalPage"));
			resultMap.put("pageNow", returnAllMap.get("pageNow"));
			resultMap.put("pageSize", preParamMap.get("pageSize"));
			resultMap.put("classId", preParamMap.get("classId"));
			logger.info("跳转班级下人员列表,参数为："+jsonStr);
			resultMap.put("result", "success");
			resultMap.put("failMsg", "");
		} catch (Exception e) {
			resultMap.put("result", "fail");
			resultMap.put("failMsg", "跳转页面失败");
			e.printStackTrace();
			logger.error("跳转班级下人员列表页面出现异常getDetailClass", e);
		} finally {
			logger.info("跳转班级下人员列表返回的结果为："+resultMap);
			PubMethods.postMed(response,mapper,resultMap);
		}

	}

	/**xzx
	 * @description 获取是否存在这些班级的任课关联信息
	 * @param 班级id集合 list String
	 * */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getDelClassMark", method = RequestMethod.POST)
	public void getDelClassMark(String jsonStr, HttpServletRequest request, HttpServletResponse response) {
		classActionImpl.getDelClassMark(jsonStr, response);
	}

	/**
	 * 导入多个班级学生
	 * @param file
	 * @param response
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/imStuExcelByManyClass", method=RequestMethod.POST)
	public void imStuExcelByManyClass(@RequestParam("file") CommonsMultipartFile file, HttpServletResponse response, HttpServletRequest request) throws Exception {
		String fileName =  file.getOriginalFilename();
		String view ="";
		String reJsonStr = "";
		ObjectMapper mapper = new ObjectMapper();
		Map<String,Object> map = new HashMap<String,Object>();

		Map<String,Object> resultMap = new HashMap<String ,Object>();
		try{
			//获取文件后缀
			String allFileName=file.getName();
			String prefix=fileName.substring(fileName.lastIndexOf(".")+1);
			if(!prefix.equals("xls")){
				resultMap.put("msg","fail");
				resultMap.put("errMsg","请将文件改为excel2003版");
				return;
			}
			String path = request.getSession().getServletContext().getRealPath("/upload/" + fileName);// 存放位置
			File destFile = new File(path);
			logger.info(destFile);
			String file1 = String.valueOf(destFile);
			FileUtils.copyInputStreamToFile(file.getInputStream(), destFile);// 复制临时文件到指定目录下
			resultMap = classActionImpl.imStuExcelByManyClass(file1);
			if(String.valueOf(resultMap.get("errMsg")).equals("null")||resultMap.get("errMsg")==null||String.valueOf(resultMap.get("errMsg")).equals("")){
				resultMap.put("errMsg","导入模板异常，请重新上传");
			}
			//将临时存到文件删除
			PubMethods.delTempFile(fileName);
		}catch(Exception e){
			e.printStackTrace();
			resultMap.put("result", "fail");
			resultMap.put("errMsg", "导入失败");
			e.printStackTrace();
			logger.error("导入多个班级学生出现异常", e);

		}finally{
			logger.info("导入多个班级学生返回的结果为"+resultMap);
			PubMethods.postMed(response,mapper,resultMap);
		}
	}

	/**
	 * @param stuorteaId
	 * @return  通过教师id获取当前教师所教授的班级信息。
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getClassListByTeaId", method = RequestMethod.POST)
	public void getClassListByTeaId(String jsonStr, HttpServletRequest request, HttpServletResponse response) throws IOException {

		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放返回值
		Map<String, Object> returnMap = new HashMap<String, Object>();
		//返回字符串
		String reJsonStr = "";
		//存放页面
		String pageName = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();

		try {
			//获取页面参数值
			Map<String, Object> preParamMap = mapper.readValue(jsonStr, returnMap.getClass());
			//获取人员列表信息
			Map<String, Object> resultAllMap = classActionImpl.getClassListByTeaId(preParamMap);
			//返回值
			resultMap.put("classList", resultAllMap.get("classList"));
			resultMap.put("result", "success");
			resultMap.put("failMsg", "");
			logger.info("跳转班级列表页面的参数为"+jsonStr);
		} catch (Exception e) {
			resultMap.put("result", "fail");
			resultMap.put("failMsg", "跳转页面失败");
			e.printStackTrace();
			logger.error("跳转班级列表页面出现异常", e);

		} finally {
			logger.info("跳转班级列表页面返回的结果为"+resultMap);
			PubMethods.postMed(response,mapper,resultMap);
		}

	}
}
